<div class="mdui-toolbar">
    <button class="mdui-btn mdui-btn-icon" mdui-menu="{target: '#filter-menu'}" id="filter-button"
        mdui-tooltip="{content: '筛选'}">
        <i class="mdui-icon material-icons">filter_list</i>
    </button>
    <div class="mdui-menu" id="filter-menu" style="transform-origin: 100% 0px; position: fixed;">
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">帖子 ID</label>
            <input class="mdui-textfield-input" type="text" id='where_id' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">用户 ID</label>
            <input class="mdui-textfield-input" type="text" id='where_user_id' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">分区 ID</label>
            <input class="mdui-textfield-input" type="text" id='where_partition' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">帖子搜索</label>
            <input class="mdui-textfield-input" type="text" id='where_search' />
        </div>
    </div>
    <select class="mdui-select" id="sort-select" mdui-select="{position: 'bottom'}">
        <option value="id,0">帖子 ID ↑</option>
        <option value="id,1" selected>帖子 ID ↓</option>
        <option value="views,0">浏览量 ↑</option>
        <option value="views,1">浏览量 ↓</option>
        <option value="goods,0">获赞量 ↑</option>
        <option value="goods,1">获赞量 ↓</option>
    </select>
    <div class="mdui-toolbar-spacer"></div>
    <button class="mdui-btn mdui-btn-raised mdui-color-theme" id="create-post" mdui-tooltip="{content: '新建实验'}">
        <i class="mdui-icon material-icons">add</i>
        新建实验
    </button>
    <button class="mdui-btn mdui-btn-icon" id="update" mdui-tooltip="{content: '刷新'}">
        <i class="mdui-icon material-icons">refresh</i>
    </button>
</div>
<div id="table"></div>
<div class="mdui-btn-group pages"></div>
<style>
    .ds-table {
        height: calc(100% - 57px - 57px);
        border-top: 1px solid rgba(0, 0, 0, .12);
        border-bottom: 1px solid rgba(0, 0, 0, .12);
    }

    /* 统一弹窗高度样式 */
    .uniform-dialog {
        min-height: 650px !important;
        max-height: 90vh !important;
        height: auto !important;
        display: flex;
        flex-direction: column;
    }

    .uniform-dialog .mdui-dialog-content {
        min-height: 550px !important;
        max-height: calc(90vh - 120px) !important;
        overflow-y: auto !important;
        height: auto !important;
        flex: 1;
        display: flex;
        flex-direction: column;
    }

    /* 分区选择器样式 */
    .partition-level-container {
        display: inline-block;
        margin-right: 10px;
        margin-bottom: 10px;
    }

    .partition-select {
        min-width: 150px;
        margin-right: 5px;
    }

    .partition-tag {
        display: inline-block;
        background-color: #2196F3;
        color: white;
        padding: 5px 10px;
        margin-right: 5px;
        margin-bottom: 5px;
        border-radius: 4px;
        font-size: 14px;
    }

    .partition-tag .remove {
        cursor: pointer;
        margin-left: 5px;
        font-weight: bold;
    }

    .partition-tag .remove:hover {
        opacity: 0.7;
    }

    .ds-selected-partitions {
        margin-top: 10px;
        min-height: 40px;
        padding: 5px;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        background-color: #fafafa;
    }

    .ds-multi-partition-selection {
        margin-bottom: 20px;
    }
</style>
<script>
    !function () {
        const $ = mdui.$;
        const tb = new table.T($("#table"));

        // 初始化表格字段
        tb.addField("#");
        tb.addField("发送人");
        tb.addField("标题");
        tb.addField("分区 (ID)");
        tb.addField("浏览量");
        tb.addField("获赞量");
        tb.addField("发布时间");
        tb.addField("置顶");
        tb.addField("精选");
        tb.addField("热帖");
        tb.addField("隐藏");
        tb.addField("操作");

        // 状态变量
        let loading = false;
        let page = 1;
        let size = 1;
        let sort_field = 'id';
        let sort_type = '1';
        let where_id = '';
        let where_partition = '';
        let where_search = '';
        let where_user_id = '';

        // 事件绑定
        $('#update').on('click', update);
        $('#create-post').on('click', createPage);
        $('#sort-select').on('change', handleSortChange);
        
        // 筛选条件变化事件
        ['where_id', 'where_partition', 'where_search', 'where_user_id'].forEach(id => {
            $(`#${id}`).on('change', () => {
                window[id] = $(`#${id}`).val();
                page = 1;
                update();
            });
        });

        // 表格点击事件
        tb.on('cellClick', ({ row, line }) => {
            if ([7, 8, 9, 10, 11].includes(line)) return;
            userDetailed(tb.getCell(row, 0));
        });

        // 排序变更处理
        function handleSortChange() {
            const v = $('#sort-select').val().split(',');
            sort_field = v[0];
            sort_type = v[1];
            page = 1;
            update();
        }

        // 检查是否有筛选条件
        function isFilter() {
            return where_id || where_partition || where_search || where_user_id;
        }

        // 更新表格数据
        function update() {
            if (loading) return;
            loading = true;

            $('#filter-button')[isFilter() ? 'addClass' : 'removeClass']('mdui-text-color-theme');
            renderPages();
            tb.clear();
            tb.startLoading();

            $.ajax({
                url: `./api/get_post_list?p=${page}` +
                    `&sort_field=${encodeURIComponent(sort_field)}` +
                    `&sort_type=${encodeURIComponent(sort_type)}` +
                    `&where_id=${encodeURIComponent(where_id)}` +
                    `&where_partition=${encodeURIComponent(where_partition)}` +
                    `&where_user_id=${encodeURIComponent(where_user_id)}` +
                    `&where_search=${encodeURIComponent(where_search)}`,
                dataType: "json",
                success: function (res) {
                    tb.endLoading();
                    loading = false;

                    if (res.code === 200) {
                        size = res.data.size;
                        $('.pages').toggle(!!size);
                        
                        res.data.data.forEach(d => {
                            const name_ = $(`<div class="mdui-chip">
                                <img class="mdui-chip-icon" src="${d.user_img}"/>
                                <span class="mdui-chip-title">${d.user_name}</span>
                            </div>`);

                            const newtab = $(`<a class="mdui-btn mdui-btn-icon" target="_blank" 
                                mdui-tooltip="{content: '在新标签页中打开'}">
                                <i class="mdui-icon material-icons">open_in_new</i>
                            </a>`).attr('href', `/post/${d.id}`);

                            const change = $(`<button class="mdui-btn mdui-btn-icon" 
                                mdui-tooltip="{content: '更改'}">
                                <i class="mdui-icon material-icons">create</i>
                            </button>`).on('click', () => changePage(d.id));

                            tb.addRow([
                                d.id,
                                { type: "el", el: name_ },
                                d.title,
                                `${d.post_partition_name} (${d.post_partition})`,
                                d.views,
                                d.goods,
                                new Date(d.time * 1000).toLocaleString(),
                                createCheckbox(d.ison, 'ison', d.id),
                                createCheckbox(d.isbest, 'isbest', d.id),
                                createCheckbox(d.ishot, 'ishot', d.id),
                                createCheckbox(d.ban, 'ban', d.id),
                                { type: 'el', el: $('<div></div>').append(newtab).append(change) }
                            ]);
                        });
                    } else {
                        mdui.snackbar(res.msg || "加载失败");
                    }
                    renderPages();
                }
            });
        }

        // 创建复选框元素
        function createCheckbox(value, field, id) {
            const label = $(`
                <label class="mdui-checkbox">
                    <input type="checkbox" ${value ? 'checked' : ''}/>
                    <i class="mdui-checkbox-icon"></i>
                </label>`);
                
            label.find('input').on('change', async function() {
                this.disabled = true;
                try {
                    await changeApi(id, { [field]: this.checked });
                } catch (e) {
                    this.checked = !this.checked;
                    mdui.snackbar(String(e) || '修改失败');
                }
                this.disabled = false;
            });
            
            return { type: "el", el: label };
        }

        // 渲染分页
        function renderPages() {
            $(".pages").html('');
            let omit = true;

            // 添加翻页按钮
            $('<button class="mdui-btn left">&lt;</button>')
                .prop("disabled", page === 1)
                .on("click", () => { page--; update(); })
                .appendTo($(".pages"));

            // 生成页码按钮
            for (let i = 0; i < size; i++) {
                const pageNum = i + 1;
                let toAdd = false;

                if (i === 0 || i === size - 1 || 
                    Math.abs(i - page + 1) < 3 || 
                    (page < 5 && i < 7) || 
                    (page > size - 5 && i > size - 7)) {
                    toAdd = true;
                }

                if (toAdd) {
                    $('<button class="mdui-btn page-num"></button>')
                        .text(pageNum)
                        .toggleClass('mdui-btn-active', pageNum === page)
                        .on("click", () => { page = pageNum; update(); })
                        .appendTo($(".pages"));
                    omit = true;
                } else if (omit) {
                    $('<button class="mdui-btn" disabled>...</button>').appendTo($(".pages"));
                    omit = false;
                }
            }

            // 添加翻页按钮
            $('<button class="mdui-btn right">&gt;</button>')
                .prop("disabled", page === size)
                .on("click", () => { page++; update(); })
                .appendTo($(".pages"));
        }

        // 查看帖子详情
        function userDetailed(id) {
            const dialog = $.dialog({
                history: false,
                cssClass: "ds-user-detailed ds-loadable ds-dialog-height",
                content: `
                    <p class='mdui-typo-subheading'>基本信息</p>
                    <table class="mdui-table mdui-shadow-0" id='ds-ud-basic'></table>
                    <p class='mdui-typo-subheading'>活跃信息</p>
                    <div class="ds-ud-activity"></div>
                    <div class="mdui-spinner"></div>
                `
            });

            const content = dialog.$element;
            window.parent.mdui.mutation();

            $.ajax({
                url: `./api/get_post_info?id=${id}`,
                dataType: "json",
                success: function (res) {
                    if (res.code !== 200) {
                        dialog.close();
                        return mdui.snackbar(res.msg || "加载失败");
                    }

                    const data = res.data;
                    content.find('.mdui-spinner').remove();

                    // 渲染基本信息表格
                    const tableData = [
                        ['帖子 ID', data.id],
                        ['帖子标题', data.title],
                        ['发送者 ID', data.user_id],
                        ['发送者 昵称', data.user_name],
                        ['分区 ID', data.partition_ids ? data.partition_ids.join(', ') : (data.post_partition || '未设置')],
                        ['分区 名称', data.partition_names ? data.partition_names.join(', ') : (data.post_partition_name || '未分类')],
                        ['发送时间', new Date(data.time * 1000).toLocaleString()],
                        ['发送者 ip', data.ip]
                    ];

                    const table = content.find('#ds-ud-basic');
                    tableData.forEach(([label, value]) => {
                        table.append(`<tr><td>${label}</td><td>${value}</td></tr>`);
                    });

                    // 渲染活跃信息
                    const activity = content.find('.ds-ud-activity');
                    const activityData = [
                        [data.views, '浏览量'],
                        [data.goods, '获赞量'],
                        [data.talks, '评论量']
                    ];

                    activityData.forEach(([value, label]) => {
                        activity.append(`<div class="ds-ud-activity-item">
                            <h3>${value}</h3>
                            <span>${label}</span>
                        </div>`);
                    });

                    dialog.handleUpdate();
                }
            });
        }

        // 调用API修改帖子信息
        function changeApi(id, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: "./api/change_post_info",
                    method: 'POST',
                    data: { id, ...data },
                    dataType: "json",
                    success: res => res.code === 200 ? resolve() : reject(res.msg),
                    error: res => reject(res.msg)
                });
            });
        }

        // 创建统一弹窗
        function createUniformDialog(title, contentHtml, buttons) {
            const dialog = $.dialog({
                history: false,
                cssClass: "ds-loadable uniform-dialog",
                title: title,
                content: contentHtml,
                buttons: buttons
            });
            
            return dialog;
        }

        /* 分区选择器核心功能 - 确保放在mdui-dialog-content下 */
        function initPartitionSelector(containerId, selectedContainerId, dialog, initialPartitionIds = [], onInitialized = null) {
            // 获取弹窗内容容器（确保是mdui-dialog-content）
            const dialogContent = dialog.$element.find('.mdui-dialog-content');
            if (!dialogContent.length) {
                console.error('未找到mdui-dialog-content容器');
                return null;
            }

            // 确保分区选择器容器在mdui-dialog-content下
            let container = $(`#${containerId}`);
            let selectedContainer = $(`#${selectedContainerId}`);
            
            // 如果容器不存在，创建并添加到dialogContent
            if (!container.length) {
                container = $(`<div id="${containerId}"></div>`);
                dialogContent.find('.ds-multi-partition-selection').append(container);
            }
            
            if (!selectedContainer.length) {
                selectedContainer = $(`<div id="${selectedContainerId}" class="ds-selected-partitions"></div>`);
                dialogContent.find('.ds-multi-partition-selection').append(selectedContainer);
            }
            
            let allPartitions = {};
            const addedPartitionIds = new Set(initialPartitionIds);
            let containerCounter = 0;

            // 加载分区数据
            $.ajax({
                url: `/api/shequ/get_post_partition/?${Date.now()}`,
                dataType: 'json',
                success: function (res) {
                    if (res && res.code === 200 && res.data) {
                        allPartitions = res.data;
                    } else {
                        // 使用模拟数据
                        allPartitions = {
                            '1': {
                                id: 1,
                                name: '生物科学',
                                parent_id: 0,
                                children: {
                                    '2': { id: 2, name: '分子生物学', parent_id: 1, children: {} },
                                    '3': { id: 3, name: '细胞生物学', parent_id: 1, children: {} }
                                }
                            },
                            '4': {
                                id: 4,
                                name: '医学研究',
                                parent_id: 0,
                                children: {
                                    '5': { id: 5, name: '临床医学', parent_id: 4, children: {} },
                                    '6': { id: 6, name: '基础医学', parent_id: 4, children: {} }
                                }
                            }
                        };
                        mdui.snackbar('加载分区数据失败，显示模拟数据');
                    }
                    
                    // 渲染层级选择器
                    renderLevelSelector(allPartitions, container, selectedContainer);
                    
                    // 回显已选分区
                    initialPartitionIds.forEach(pid => {
                        const partitionInfo = findPartitionById(allPartitions, pid);
                        if (partitionInfo) {
                            const fullPath = getPartitionFullPath(allPartitions, pid);
                            addPartitionTag(pid, fullPath, selectedContainer);
                        }
                    });
                    
                    if (typeof onInitialized === 'function') {
                        onInitialized();
                    }
                },
                error: function () {
                    allPartitions = createMockPartitions();
                    renderLevelSelector(allPartitions, container, selectedContainer);
                    mdui.snackbar('加载分区数据失败，显示模拟数据');
                    if (typeof onInitialized === 'function') onInitialized();
                }
            });

            // 创建模拟分区数据
            function createMockPartitions() {
                return {
                    '1': {
                        id: 1,
                        name: '生物科学',
                        parent_id: 0,
                        children: {
                            '2': { id: 2, name: '分子生物学', parent_id: 1, children: {} },
                            '3': { id: 3, name: '细胞生物学', parent_id: 1, children: {} }
                        }
                    },
                    '4': {
                        id: 4,
                        name: '医学研究',
                        parent_id: 0,
                        children: {
                            '5': { id: 5, name: '临床医学', parent_id: 4, children: {} },
                            '6': { id: 6, name: '基础医学', parent_id: 4, children: {} }
                        }
                    }
                };
            }

            // 递归查找分区
            function findPartitionById(partitions, id) {
                for (const p of Object.values(partitions)) {
                    if (p.id == id) return p;
                    if (p.children && Object.keys(p.children).length) {
                        const found = findPartitionById(p.children, id);
                        if (found) return found;
                    }
                }
                return null;
            }

            // 获取分区完整路径
            function getPartitionFullPath(partitions, id) {
                const path = [];
                let current = findPartitionById(partitions, id);
                if (!current) return '';
                
                path.push(current.name);
                let parentId = current.parent_id;
                
                while (parentId) {
                    const parent = findPartitionById(partitions, parentId);
                    if (parent) {
                        path.unshift(parent.name);
                        parentId = parent.parent_id;
                    } else break;
                }
                
                return path.join(' > ');
            }

            // 渲染层级选择器
            function renderLevelSelector(partitions, container, selectedContainer) {
                container.empty();
                
                const levelContainer = $('<div class="partition-level-container"></div>').appendTo(container);
                const select = $('<select class="mdui-select partition-select"><option value="">请选择分区</option></select>');
                const addButton = $(`<button class="mdui-btn mdui-btn-raised mdui-color-primary mdui-btn-sm" disabled>添加此分区</button>`);
                
                levelContainer.append(select).append(addButton);
                
                // 添加选项
                Object.values(partitions).forEach(partition => {
                    select.append(`<option value="${partition.id}">${partition.name}</option>`);
                });
                
                // 初始化选择框
                try {
                    const mduiInstance = typeof mdui !== 'undefined' ? mdui : window.parent.mdui;
                    new mduiInstance.Select(select[0]);
                    mduiInstance.mutation();
                } catch (e) {
                    console.error(`初始化选择框失败: ${e.message}`);
                }

                // 选择事件
                select.on('change', function () {
                    const selectedId = $(this).val();
                    addButton.prop('disabled', !selectedId);
                    
                    if (!selectedId) return;
                    
                    const selectedPartition = findPartitionById(allPartitions, selectedId);
                    if (!selectedPartition) return;
                    
                    // 清除后续选择器
                    levelContainer.nextAll().remove();
                    
                    if (selectedPartition?.children && Object.keys(selectedPartition.children).length) {
                        containerCounter++;
                        const nextContainer = $(`<div id="next-level-container-${containerCounter}"></div>`);
                        levelContainer.after(nextContainer);
                        renderNextLevelSelector(selectedPartition.children, nextContainer, selectedContainer);
                    }
                });

                // 添加按钮事件
                addButton.on('click', () => {
                    const selectedId = select.val();
                    if (selectedId && !addedPartitionIds.has(parseInt(selectedId))) {
                        const fullPath = getPartitionFullPath(allPartitions, selectedId);
                        addPartitionTag(selectedId, fullPath, selectedContainer);
                        window.parent.mdui.mutation();
                    } else if (addedPartitionIds.has(parseInt(selectedId))) {
                        mdui.snackbar('该分区已添加');
                    }
                });
            }

            // 渲染下一级选择器
            function renderNextLevelSelector(partitions, container, selectedContainer) {
                container.empty();
                
                const levelContainer = $('<div class="partition-level-container"></div>').appendTo(container);
                const select = $('<select class="mdui-select partition-select"><option value="">请选择子分区</option></select>');
                const addButton = $(`<button class="mdui-btn mdui-btn-raised mdui-color-primary mdui-btn-sm" disabled>添加此分区</button>`);
                
                levelContainer.append(select).append(addButton);
                
                // 添加选项
                Object.values(partitions).forEach(partition => {
                    select.append(`<option value="${partition.id}">${partition.name}</option>`);
                });
                
                // 初始化选择框
                try {
                    const mduiInstance = typeof mdui !== 'undefined' ? mdui : window.parent.mdui;
                    new mduiInstance.Select(select[0]);
                    mduiInstance.mutation();
                } catch (e) {
                    console.error(`初始化子选择框失败: ${e.message}`);
                }

                // 选择事件和添加按钮事件与上一级类似
                select.on('change', function () {
                    const selectedId = $(this).val();
                    addButton.prop('disabled', !selectedId);
                    
                    if (!selectedId) return;
                    
                    const selectedPartition = findPartitionById(allPartitions, selectedId);
                    if (!selectedPartition) return;
                    
                    // 清除后续选择器
                    container.nextAll().remove();
                    
                    if (selectedPartition?.children && Object.keys(selectedPartition.children).length) {
                        containerCounter++;
                        const nextContainer = $(`<div id="next-level-container-${containerCounter}"></div>`);
                        container.after(nextContainer);
                        renderNextLevelSelector(selectedPartition.children, nextContainer, selectedContainer);
                    }
                });

                addButton.on('click', () => {
                    const selectedId = select.val();
                    if (selectedId && !addedPartitionIds.has(parseInt(selectedId))) {
                        const fullPath = getPartitionFullPath(allPartitions, selectedId);
                        addPartitionTag(selectedId, fullPath, selectedContainer);
                        window.parent.mdui.mutation();
                    } else if (addedPartitionIds.has(parseInt(selectedId))) {
                        mdui.snackbar('该分区已添加');
                    }
                });
            }

            // 添加分区标签
            function addPartitionTag(id, name, selectedContainer) {
                const numericId = parseInt(id);
                if (addedPartitionIds.has(numericId)) return;
                
                const tag = $(`<div class="partition-tag" data-id="${numericId}">${name} <span class="remove">×</span></div>`);
                tag.find('.remove').on('click', () => {
                    tag.remove();
                    addedPartitionIds.delete(numericId);
                    window.parent.mdui.mutation();
                });
                
                selectedContainer.append(tag);
                addedPartitionIds.add(numericId);
            }

            // 返回公共接口
            return {
                getSelectedPartitionIds: () => Array.from(addedPartitionIds)
            };
        }

        // 修改帖子
        function changePage(id) {
            let saving = false;
            let content, partitionSelector;
            
            // 创建对话框
            const dialog = createUniformDialog('修改帖子', `
                <div class="mdui-textfield">
                    <label class="mdui-textfield-label">标题</label>
                    <input class="mdui-textfield-input" type="text" id="ds-change-title" maxlength="100" required />
                    <div class="mdui-textfield-error">标题不能为空</div>
                </div>
                <div class="mdui-textfield">
                    <label class="mdui-textfield-label">发送者 ID</label>
                    <input class="mdui-textfield-input" type="text" id="ds-change-user-id" required />
                    <div class="mdui-textfield-error">发送者 ID 不能为空</div>
                </div>
                <div class="ds-multi-partition-selection">
                    <label class="mdui-textfield-label">分区选择（可多选）</label>
                    <div id="ds-change-partition-container"></div>
                    <div id="ds-selected-partitions" class="ds-selected-partitions"></div>
                </div>
                <div class="mdui-textfield">
                    <label class="mdui-textfield-label">内容（MarkDown）</label>
                    <textarea class="mdui-textfield-input" id="ds-change-text" maxlength="100000" required></textarea>
                    <div class="mdui-textfield-error">内容不能为空</div>
                </div>
                <div class="mdui-spinner"></div>
            `, [
                { text: '取消', close: true },
                { text: '保存', close: false, onClick: saveHandler }
            ]);

            content = dialog.$element;

            // 保存按钮处理
            function saveHandler() {
                if (content.find('.mdui-spinner').length || saving) return false;
                if (!partitionSelector) {
                    return mdui.snackbar('分区选择器尚未初始化完成');
                }

                const title = content.find('#ds-change-title').val();
                const user_id = content.find('#ds-change-user-id').val();
                const text = content.find('#ds-change-text').val();
                const selectedPartitionIds = partitionSelector.getSelectedPartitionIds();
                
                if (!title || !user_id || !text || !selectedPartitionIds.length) {
                    return mdui.snackbar('请填写所有必填字段并选择分区');
                }

                content.find('input,a,select,textarea').attr('disabled', '');
                saving = true;

                changeApi(id, { title, user_id, text, partition_ids: selectedPartitionIds })
                    .then(() => {
                        dialog.close();
                        update();
                        saving = false;
                        mdui.snackbar('修改成功');
                    }, (msg) => {
                        saving = false;
                        content.find('input,a,select,textarea').removeAttr('disabled');
                        mdui.snackbar(msg || '修改失败');
                    });
                return false;
            }

            // 加载帖子信息
            $.ajax({
                url: `./api/get_post_info?id=${id}`,
                dataType: 'json',
                success: function (res) {
                    if (res.code !== 200) {
                        dialog.close();
                        return mdui.snackbar(res.msg || '加载失败');
                    }

                    const data = res.data;
                    content.find('#ds-change-title').val(data.title);
                    content.find('#ds-change-user-id').val(data.user_id);
                    content.find('#ds-change-text').val(data.text);

                    const postPartitionIds = data.partition_ids || (data.post_partition ? [data.post_partition] : []);
                    
                    // 初始化分区选择器，传入dialog确保放在正确位置
                    setTimeout(() => {
                        partitionSelector = initPartitionSelector(
                            'ds-change-partition-container', 
                            'ds-selected-partitions',
                            dialog,
                            postPartitionIds, 
                            () => {
                                content.find('.mdui-spinner').remove();
                                setTimeout(() => {
                                    try {
                                        window.parent.mdui.mutation();
                                        dialog.handleUpdate();
                                    } catch (e) { 
                                        console.error(`对话框更新失败: ${e.message}`); 
                                    }
                                }, 100);
                            }
                        );
                    }, 100);
                },
                error: () => {
                    dialog.close();
                    mdui.snackbar('加载帖子信息失败');
                }
            });
        }

        // 创建新帖子
        function createPage() {
            let saving = false;
            let content, partitionSelector;
            
            // 创建对话框
            const dialog = createUniformDialog("新建实验", `
                <div class="mdui-textfield">
                    <label class="mdui-textfield-label">标题</label>
                    <input class="mdui-textfield-input" type="text" id='ds-create-title' maxlength="100" required />
                    <div class="mdui-textfield-error">标题不能为空</div>
                </div>
                <div class="mdui-textfield">
                    <label class="mdui-textfield-label">发送者 ID</label>
                    <input class="mdui-textfield-input" type="text" id='ds-create-user-id' required />
                    <div class="mdui-textfield-error">发送者 ID 不能为空</div>
                </div>
                <div class="ds-multi-partition-selection">
                    <label class="mdui-textfield-label">分区选择（可多选）</label>
                    <div id="ds-create-partition-container"></div>
                    <div id="ds-create-selected-partitions" class="ds-selected-partitions"></div>
                </div>
                <div class="mdui-textfield">
                    <label class="mdui-textfield-label">内容（MarkDown）</label>
                    <textarea class="mdui-textfield-input" id='ds-create-text' maxlength="100000" required ></textarea>
                    <div class="mdui-textfield-error">内容不能为空</div>
                </div>
                <div class="mdui-spinner"></div>
            `, [
                { text: '取消', close: true },
                { text: '发布', close: false, onClick: publishHandler }
            ]);

            content = dialog.$element;
            
            // 发布按钮处理
            function publishHandler() {
                if (content.find('.mdui-spinner').length || saving) return false;

                const title = content.find('#ds-create-title').val();
                const user_id = content.find('#ds-create-user-id').val();
                const text = content.find('#ds-create-text').val();
                const selectedPartitionIds = partitionSelector.getSelectedPartitionIds();
                
                if (!title || !user_id || !text || !selectedPartitionIds.length) {
                    return mdui.snackbar("请填写所有必填字段并选择分区");
                }

                content.find('input,a,select,textarea').attr('disabled', '');
                saving = true;

                $.ajax({
                    url: "./api/create_post",
                    method: 'POST',
                    data: { title, user_id, text, partition_ids: selectedPartitionIds },
                    dataType: "json",
                    success(res) {
                        if (res.code === 200) {
                            dialog.close();
                            update();
                            saving = false;
                            return mdui.snackbar("创建成功");
                        }
                        saving = false;
                        content.find('input,a,select,textarea').removeAttr('disabled');
                        return window.parent.mdui.snackbar(res.msg || "创建失败");
                    },
                    error() {
                        saving = false;
                        content.find('input,a,select,textarea').removeAttr('disabled');
                        return window.parent.mdui.snackbar("创建失败");
                    }
                });
                return false;
            }
            
            // 初始化分区选择器，传入dialog确保放在正确位置
            setTimeout(() => {
                partitionSelector = initPartitionSelector(
                    'ds-create-partition-container', 
                    'ds-create-selected-partitions',
                    dialog,
                    [], 
                    () => {
                        content.find('.mdui-spinner').remove();
                        setTimeout(() => {
                            try {
                                window.parent.mdui.mutation();
                                dialog.handleUpdate();
                            } catch (e) { 
                                console.error(`对话框更新失败: ${e.message}`); 
                            }
                        }, 100);
                    }
                );
            }, 100);
        }

        // 初始化页面
        update();
    }();
</script>
